package com.jule.teenpatti.game.network.protocol.reqs;

import JoloProtobuf.GameSvr.JoloGame;
import com.jule.core.common.log.LoggerUtils;
import com.jule.core.jedis.StoredObjManager;
import com.jule.core.utils.TimeUtil;
import com.jule.teenpatti.base.dao.bean.TaskConfigModel;
import com.jule.teenpatti.base.dao.bean.TaskLineConfigModel;
import com.jule.teenpatti.base.dao.bean.TaskUserHistModel;
import com.jule.teenpatti.base.enums.ErrorCodeEnum;
import com.jule.teenpatti.base.enums.GameConst;
import com.jule.teenpatti.base.enums.RedisConst;
import com.jule.teenpatti.game.dao.TaskDBUtil;
import com.jule.teenpatti.game.dao.bean.TaskUserAwardLogModel;
import com.jule.teenpatti.game.model.PlayerInfo;
import com.jule.teenpatti.game.network.protocol.ClientReq;
import com.jule.teenpatti.game.network.protocol.acks.JoloGame_TaskAwardAck_50062;
import com.jule.teenpatti.game.play.AbstractTable;
import com.jule.teenpatti.game.play.TableUtil;
import com.jule.teenpatti.game.service.TableService;
import com.jule.teenpatti.game.service.TaskService;
import com.jule.teenpatti.game.vavle.notice.NoticeBroadcastMessages;
import com.jule.teenpatti.log.service.LogReasons;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.List;

@Slf4j
public class JoloGame_TaskAwardReq_50062 extends ClientReq {
    private long time;

    public JoloGame_TaskAwardReq_50062(int functionId) {
        super(functionId);
    }

    private JoloGame.JoloGame_TaskAwardsReq req;

    @Override
    public void readPayLoadImpl(ByteBuf buf) throws Exception {
        time = System.currentTimeMillis();
        byte[] blob = new byte[buf.readableBytes()];
        buf.readBytes(blob);
        req = JoloGame.JoloGame_TaskAwardsReq.parseFrom(blob);
        AbstractTable table = TableService.getInstance().getTable(header.gameId + "", req.getRoomId(), req.getTableId());
        if (null != table) {
            this.setTable(table);
        } else {
            log.error("桌子不存在,roomId->" + req.getRoomId() + ", tableId->" + req.getTableId());
        }
    }

    @Override
    public void processImpl() throws Exception {
        log.debug("收到消息-> " + functionId + ", reqNum-> " + header.reqNum + ", req->" + req.toString());
        try {
            Long taskId = req.getTaskId();
            String userId = req.getUserId();
            JoloGame.JoloGame_TaskAwardsAck.Builder ack = JoloGame.JoloGame_TaskAwardsAck.newBuilder();
            ack.setResult(1)
                    .setRoomId(req.getRoomId())
                    .setTableId(req.getTableId())
                    .setUserId(userId);


            AbstractTable table = getTable();
            PlayerInfo player = table.getPlayer(userId);

            boolean b = TaskService.getInstance().checkTimePeriod(userId, taskId);
            if (!b) {
                ack.setResult(0);
                ack.setResultMsg(ErrorCodeEnum.GAME_50062_1.getCode());
                ack.setCurrPlayScore(0);
                ctx.writeAndFlush(new JoloGame_TaskAwardAck_50062(ack.build(), header));
                return;
            }
            //查看这个任务有没有
            TaskUserHistModel userTask = TaskService.getInstance().checkTaskAward(userId, taskId);
            if (userTask == null) {
                log.debug("have no the task taskId{},userId{},tableInfo{} ", taskId, userId, TableUtil.toStringNormal(table));
                return;
            }
            //根据任务Id,找到相应奖励
            int taskConfigId = userTask.getTaskId();

            int val = TaskService.getInstance().getValueBy(userId, "" + header.gameId, userTask.getTaskType());
            if (userTask.getTaskTargetValue() > val) {
                return;
            }

            List<JoloGame.JoloGame_TaskAwardInfo> awardInfos = TaskService.getInstance().getTaskAwardInfo(taskConfigId);
            Iterator<JoloGame.JoloGame_TaskAwardInfo> iter = awardInfos.iterator();
            while (iter.hasNext()) {
                JoloGame.JoloGame_TaskAwardInfo model = iter.next();
                if (model.getType() == 1) {
                    player.addPlayScoreStore(model.getNum(), LogReasons.CommonLogReason.TASK_AWARD);
                    //发送通知
                    NoticeBroadcastMessages.moneyChangeNotice(table,userId,player.getPlayScoreStore());
                }
                TaskConfigModel taskConf = StoredObjManager.hget(
                        RedisConst.TASK_CONFIG_TASK.getProfix(),
                        RedisConst.TASK_CONFIG_TASK.getField() + userTask.getTaskId(), TaskConfigModel.class);

                TaskLineConfigModel taskLineConfigModel = StoredObjManager.hget(RedisConst.TASK_CONFIG_LINE.getProfix(),
                        RedisConst.TASK_CONFIG_LINE.getField() + userTask.getLineId(), TaskLineConfigModel.class);
                TaskUserAwardLogModel taskAwardLog = new TaskUserAwardLogModel();
                taskAwardLog.setItemId(model.getItemId());
                taskAwardLog.setItemNum(model.getNum());
                taskAwardLog.setSuccAward((byte) 1);
                taskAwardLog.setTaskBeginTime(taskLineConfigModel.getBeginTime());
                taskAwardLog.setTaskEndTime(taskLineConfigModel.getEndTime());
                taskAwardLog.setTaskGameId("" + header.gameId);
                taskAwardLog.setTaskName(taskConf.getTaskName());
                taskAwardLog.setTaskId(userTask.getTaskId());
                taskAwardLog.setTaskType((byte) model.getType());
                taskAwardLog.setTaskTargetValue(taskConf.getTaskTargetValue());

                TaskDBUtil.insertUserTaskAwardLog(taskAwardLog);
            }
            ack.addAllTaskRewards(awardInfos);
            //移除缓存中任务修改task_user_stat的进度，
            userTask.setTaskStatus((byte) 1);
            int result = TaskDBUtil.updateByPrimaryKey(userTask);
            if (result == 1) {

                //清空统计
                TaskService.getInstance().clearUserTaskStat(userId, "" + header.gameId, userTask.getTaskType());
                TaskService.getInstance().delUserTask(userTask);
                //找下一任务，首先看时间段
                TaskLineConfigModel taskLineConfig = StoredObjManager.hget(RedisConst.TASK_CONFIG_LINE.getProfix(),
                        RedisConst.TASK_CONFIG_LINE.getField() + userTask.getLineId(),
                        TaskLineConfigModel.class);
                long beginTime = TimeUtil.getDateToMillis(taskLineConfig.getBeginTime());
                long endTime = TimeUtil.getDateToMillis(taskLineConfig.getEndTime());
                long currentTime = System.currentTimeMillis();
                if (currentTime > beginTime && currentTime < endTime) {//找下一个

                    TaskUserHistModel task = TaskService.getInstance().getNextTask(userTask);
                    TaskConfigModel taskConfig = StoredObjManager.hget(RedisConst.TASK_CONFIG_TASK.getProfix(),
                            RedisConst.TASK_CONFIG_TASK.getField() + task.getTaskId(), TaskConfigModel.class);
                    JoloGame.JoloGame_TaskInfo.Builder taskInfo = JoloGame.JoloGame_TaskInfo.newBuilder();
                    taskInfo.setTaskId(task.getId());
                    taskInfo.setTaskName(taskConfig.getTaskName());
                    taskInfo.setTaskIcon(taskConfig.getTaskIcon());
                    taskInfo.setTaskType(task.getTaskType());
                    taskInfo.setTaskDesc(taskConfig.getTaskDesc());
                    taskInfo.setGameId(task.getTaskGameId());
                    taskInfo.addAllTaskAwards(TaskService.getInstance().getTaskAwardInfo(userTask.getTaskId()));
                    taskInfo.setTargetValue(task.getTaskTargetValue());
                    taskInfo.setValue(TaskService.getInstance().getValueBy(userId, "" + header.gameId, task.getTaskType()));
                    ack.setTaskInfo(taskInfo.build());
                }
            }
            ack.setCurrPlayScore(player.getPlayScoreStore());
            ctx.writeAndFlush(new JoloGame_TaskAwardAck_50062(ack.build(), header));
            long timeMillis = System.currentTimeMillis() - time;
            if (timeMillis > GameConst.COST_TIME) {
                LoggerUtils.performance.info("TaskAwardReq_50062,cost time:{},req:{}", timeMillis, req.toString());
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        } finally {
        }

    }

}
